package com.netbao.sys.service.impl;

import com.netbao.model.CAttributes;
import com.netbao.model.CNode;
import com.netbao.model.StatusCode;
import com.netbao.sys.model.Resources;
import com.netbao.sys.model.User;
import com.netbao.sys.utils.ShiroUtils;
import com.netbao.sys.vomapper.ResourceMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service
public class ResourceServiceImpl implements com.netbao.sys.service.ResourceService {
    @Resource
    private ResourceMapper resourceMapper;
    @Override
    public Object getmeun() {
        User currentUser = (User) ShiroUtils.getSessionAttribute(StatusCode.SESSIONUSER);
//        System.out.println(currentUser);
        List<Resources> resources = resourceMapper.getmenu(currentUser.getId());
//        System.out.println(resources);
        return creatTree(resources,-1);
    }

    @Override
    public Object getRolesidByRes(Long id) {
        List<Resources> resources = resourceMapper.getRolesidByRes(id);
//        System.out.println(resources);
        return creatTree(resources,-1);
    }

    private List<CNode> creatTree(List<Resources> resources, Integer pid) {
        List<CNode> nodes=new ArrayList<>();
        for (Resources res : resources) {
            if(res.getPid().equals(pid)){
                CNode node=new CNode();
                node.setId(res.getId())
                        .setText(res.getCname())
                        .setIconCls(res.getIcon())
                        .setChecked(res.getIsdel());
                if(res.getIsmenuLeaf()){
                    node.setState("open");
                    CAttributes attributes=new CAttributes();
                    attributes.setUrl(res.getUrl());
                    node.setAttributes(attributes);
                }else {
                    node.setState("close")
                            .setChildren(creatTree(resources,res.getId()));
                }
                nodes.add(node);
            }
        }
        return nodes;
    }
}
